#!/usr/bin/python
# coding:utf8
import smtplib  
from email.MIMEText import MIMEText  
from email.Utils import formatdate  
from email.Header import Header  
import sys  
import string
import psutil
import datetime
import uuid
import socket
import fcntl
import struct
  
#设置默认字符集为UTF8 不然有些时候转码会出问题  
default_encoding = 'utf-8'  
if sys.getdefaultencoding() != default_encoding:  
    reload(sys)  
    sys.setdefaultencoding(default_encoding)  
   
#发送邮件的相关信息，根据你实际情况填写  
smtpHost = 'smtp.exmail.qq.com'  
smtpPort = '25'  
sslPort  = '465'  
fromMail = 'fwqjk@rshui.cn'  
toMail   = 'zangxuefeng@rshui.cn'
toMail2='756686600@qq.com'  
username = 'fwqjk@rshui.cn'  
password = 'Fwqjk@123'  
ipduan = '222.92.129.130'
ipduan2='58.240.192.248'
users_count = len(psutil.users())
stringa=str(psutil.users())
stringb=stringa.split('host=')
#邮件标题和内容
starttime = datetime.datetime.now()
userinfo = psutil.users()
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24]) 
subject  = u'服务器登陆信息'
text = "IP地址是  " + get_ip_address('eth0') + "  的服务器在" + str(starttime) + "有人登录。 登录者的信息是 " + str(userinfo)
body = string.join((
                  # "From: %s" % fromMail,
                  # "To: %s" % toMail,
                  # "Subject: %s" % subject,
                   "",
                   text
                   ),"\r\n")
  
#body     = u'hello,this is from rshui.com ' + fromMail  
#初始化邮件  
encoding = 'utf-8'  
mail = MIMEText(body.encode(encoding),'plain',encoding)  
mail['Subject'] = Header(subject,encoding)  
mail['From'] = fromMail  
mail['To'] = toMail  
mail['Date'] = formatdate()  
  
    #smtp = smtplib.SMTP(smtpHost,smtpPort)  
    #smtp.ehlo()  
    #smtp.login(username,password)  
  
    #tls加密方式，通信过程加密，邮件数据安全，使用正常的smtp端口  
    #smtp = smtplib.SMTP(smtpHost,smtpPort)  
    #smtp.set_debuglevel(True)  
    #smtp.ehlo()  
    #smtp.starttls()  
    #smtp.ehlo()  
    #smtp.login(username,password)
if users_count >0:
    for n in range(1,users_count+1):
        if  stringb[n].split('\'')[1] != ipduan and stringb[n].split('\'')[1] !=ipduan2:
               #纯粹的ssl加密方式，通信过程加密，邮件数据安全  
            smtp = smtplib.SMTP_SSL(smtpHost,sslPort)  
            smtp.ehlo()  
            smtp.login(username,password)  
            #发送邮件  
            smtp.sendmail(fromMail,toMail2,mail.as_string())  
            smtp.sendmail(fromMail,toMail,mail.as_string())  
            smtp.close() 
        else:
             print 'not send'
             pass
else:
    pass 
